import { Injectable } from '@angular/core';

import { Http } from '@angular/http';

import { TranslatePipe } from '../translate';

declare var XLSX: any;
declare var saveAs: any;

@Injectable()
export class Util {

  constructor(private http: Http,private _translatePipe:TranslatePipe) {

  }
      
  get(params) {


    return this.http.get(params.url, { "search": params.data }).map((res) => {
      res = res.json();
    });

  }
  // 通用
  columnHiddenHandel(columns, timeType) {
    for (let i in columns) {
      let item = columns[i];

      if (typeof item.hidden != "undefined") {
        item.hidden = !(timeType == item.mark);
        // console.log(this.timeType+"  "+item.mark);
        // console.log(this.timeType == item.mark);
      } else {
        continue;
      }
    }
  }
  sortHandel(param) {
 
      param.sort = "sellMoney";
      param.sortType = "desc";
  }

  // 总和计算
  getSellAllResult(obj, data) {

    for (let i in data) {
      let item = data[i];

      for (let key in obj) {

        obj[key] += item[key];
      }
    }

    /*console.log('hhhh///');
    console.log(obj);*/
    return obj;


  }

  // 本地保存
  store() {

    return {

      set: function(key, value) {

        try {
          if (typeof value != 'string') {

            value = JSON.stringify(value);
          }
        } catch (oException) {
          console.log(oException);
        }


        // 存储
        try {
          localStorage.setItem(key, value);
        } catch (oException) {
          if (oException.name == 'QuotaExceededError') {
            console.log('超出本地存储限额！');
            //如果历史信息不重要了，可清空后再设置
            localStorage.clear();
            localStorage.setItem(key, value);
          }
        }

      },
      get: function(key) {

        let value = localStorage.getItem(key);

        if (value === null) {

        } else {
          try {
            value = JSON.parse(value);
          } catch (oException) {
            console.log(value);
            console.log(oException.name);

          }

        }

        return value;

      },
      has: function(key) {

        let bool: boolean = false;

        if (localStorage.getItem(key) === null) {
          bool = false;
        } else {
          bool = true;
        }

        return bool;

      },
      delete: function(key) {

        if (this.has(key)) {
          localStorage.removeItem(key);
        } else {

        }

      },
      clear: function() {
        localStorage.clear();
      }
    };
  }


  // 临时保存
  sessionStore() {
    return {

      set: function(key, value) {

        try {
          if (typeof value != 'string') {

            value = JSON.stringify(value);
          }
        } catch (oException) {
          console.log(oException);
        }


        // 存储
        try {
          sessionStorage.setItem(key, value);
        } catch (oException) {
          if (oException.name == 'QuotaExceededError') {
            console.log('超出本地存储限额！');
            //如果历史信息不重要了，可清空后再设置
            sessionStorage.clear();
            sessionStorage.setItem(key, value);
          }
        }

      },
      get: function(key) {

        let value: any = sessionStorage.getItem(key);

        if (value === null) {

        } else {
          try {
            value = JSON.parse(value);
          } catch (oException) {
            console.log(value);
            console.log(oException.name);

          }

        }

        return value;

      },
      has: function(key) {

        let bool: boolean = false;

        if (sessionStorage.getItem(key) === null) {
          bool = false;
        } else {
          bool = true;
        }

        return bool;

      },
      delete: function(key) {

        if (this.has(key)) {
          sessionStorage.removeItem(key);
        } else {

        }

      },
      clear: function() {
        sessionStorage.clear();
      }
    };
  }

  export(data, fileName = "下载"): void {


    /* generate worksheet */
    const ws = XLSX.utils.aoa_to_sheet(data);

    /* generate workbook and add the worksheet */
    const wb = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');

    /* save to file */
    const wbout = XLSX.write(wb, { bookType: 'xlsx', type: 'binary' });
    console.log(fileName);
    saveAs(new Blob([this.s2ab(wbout)]), fileName + '.xlsx');
  }
  s2ab(s) {
    var buf = new ArrayBuffer(s.length);
    var view = new Uint8Array(buf);
    for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
    return buf;
  }
  jsonToArrry(data, dims, exportDimText) {

    var temp = [];

    let _title = [];

    for(let t in exportDimText){
    	_title.push(this._translatePipe.transform(exportDimText[t],[]));
    }

    temp.push(_title);

    if (Array.isArray(data)) {

      for (var k = 0; k < data.length; k++) {

        var item = data[k];

        var _temp = [];

        for (var j = 0; j < dims.length; j++) {

          _temp.push(item[dims[j]]);
        }

        temp.push(_temp);
      }

    }

    return temp;

  }

  isEmptyObject(obj) {
    for (var i in obj) {
      if (obj.hasOwnProperty(i)) {
        return false;
      }
    }
    return true;
  }

  isDate(value) {
    return Object.prototype.toString.call(value) === '[object Date]';
  }

  isRegExp(value) {
    return Object.prototype.toString.call(value) === '[object RegExp]';
  }

  isWindow(obj) {
    return obj && obj.window === obj;
  }

  isFunction(value) {
    return typeof value === 'function';
  }

  isDefined(value) {
    return typeof value !== 'undefined';
  }

  equals(o1, o2) {

    if (o1 === o2) {
      return true;
    }

    if (o1 === null || o2 === null) {
      return false;
    }

    if (o1 !== o1 && o2 !== o2) {
      return true; // NaN === NaN
    }

    const t1 = typeof o1;

    const t2 = typeof o2;

    let length;
    let key;
    let keySet;

    if (t1 === t2 && t1 === 'object') {
      if (Array.isArray(o1)) {
        if (!Array.isArray(o2)) {
          return false;
        }
        if ((length = o1.length) === o2.length) {
          for (key = 0; key < length; key++) {
            if (!this.equals(o1[key], o2[key])) {
              return false;
            }
          }
          return true;
        }
      } else if (this.isDate(o1)) {
        if (!this.isDate(o2)) {
          return false;
        }
        return this.equals(o1.getTime(), o2.getTime());

      } else if (this.isRegExp(o1)) {
        if (!this.isRegExp(o2)) {
          return false;
        }
        return o1.toString() === o2.toString();
      } else {
        if (this.isWindow(o1) || this.isWindow(o2) || Array.isArray(o2) || this.isDate(o2) || this.isRegExp(o2)) {
          return false;
        }

        keySet = Object.create(null);

        for (key in o1) {
          if (key.charAt(0) === '$' || this.isFunction(o1[key])) {
            continue
          }
          if (!this.equals(o1[key], o2[key])) {
            return false;
          }
          keySet[key] = true;
        }
        for (key in o2) {
          if (!(key in keySet) &&
            key.charAt(0) !== '$' &&
            this.isDefined(o2[key]) &&
            !this.isFunction(o2[key])
          ) {
            return false;
          }
        }


        return true;
      }
    }
    return false;
  }

  // 平均数
  avgPrice(money, mount) {

    let avg: number = 0;

    if (mount && mount > 0) {

      avg = Number((Number(money) / Number(mount)).toFixed(2));

    } else {
      avg = 0;
    }

    if (isNaN(avg)) {
      avg = 0;
    }

    return avg;

  }

  // 店铺等级
  shopLevels(shop) {

    if (typeof shop.shopLevel == "undefined") {
      return shop;
    }


    if (shop.shopLevel >= 1 && shop.shopLevel <= 5) {
      shop.shopLevelType = 1;
    } else if (shop.shopLevel >= 6 && shop.shopLevel <= 10) {
      shop.shopLevelType = 2;
    } else if (shop.shopLevel >= 11 && shop.shopLevel <= 15) {
      shop.shopLevelType = 3;
    } else {
      shop.shopLevelType = 4;
    }

    let shopLevel = (shop.shopLevel - 1) % 5 + 1;
    shop.shopLevels = new Array(shopLevel);

    return shop;
  }


  parseURL(url) {
    var a = document.createElement('a');
    a.href = url;
    return {
      source: url,
      protocol: a.protocol.replace(':', ''),
      host: a.hostname,
      port: a.port,
      query: a.search,
      params: (function() {
        var ret = {},
          seg = a.search.replace(/^\?/, '').split('&'),
          len = seg.length, i = 0, s;
        for (; i < len; i++) {
          if (!seg[i]) { continue; }
          s = seg[i].split('=');
          ret[s[0]] = s[1];
        }
        return ret;
      })(),
      file: (a.pathname.match(/\/([^\/?#]+)$/i) || [, ''])[1],
      hash: a.hash.replace('#', ''),
      path: a.pathname.replace(/^([^\/])/, '/$1'),
      relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [, ''])[1],
      segments: a.pathname.replace(/^\//, '').split('/')
    };
  }

}
